<template>
  <div class="login">
    <van-image width="100%" height="150" src="/static/img/banner.jpg" />
    <van-button
      type="primary"
      :disabled="disabled"
      size="large"
      @click="wxLogin"
      >微信用户一键登录</van-button
    >
    <div class="login-account">
      <navigator url="../loginAccount/index">手机号验证注册/登录</navigator>
      <!-- <button
        class="show"
        type="primary"
        lang="zh_CN"
        open-type="getPhoneNumber"
        @getphonenumber="getPhoneNumber1"
      >
        获取用户手机号
      </button> -->
    </div>
  </div>
</template>

<script>
import store from "@/utils/store.js";
export default {
  config: {
    navigationBarTitleText: "登录",
  },
  data() {
    return {
      user: { nickName: "立即登录" },
      wxCode: String,
      disabled: true,
    };
  },
  onShow() {
    let _page = this;
    wx.login({
      success(res) {
        console.log("res>>", res);
        if (res.code) {
          console.log("----", res.code);
          _page.wxCode = res.code;
          _page.disabled = false;
        } else {
          console.log("登录失败！" + res.errMsg);
        }
      },
    });
  },
  methods: {
    getPhoneNumber1(opt) {
      console.log("opt", opt);
    },
    wxLogin() {
      let that = this;

      wx.getUserProfile({
        desc: "用于获取用户信息",
        success: (res) => {
          console.log("用户信息---", res);

          const userInfo1 = JSON.parse(res.rawData);
          // 要获取手机号
          let loginInfo = {
            code: that.wxCode,
            mobile: "18018772040",
          };

          that.$API.post("/wechat/getWxOpenId", loginInfo).then((res1) => {
            console.log(res1);
            //将用户数据写入缓存
            const resData = res1.data;
            const userInfo = {
              avatarUrl: userInfo1.avatarUrl,
              nickName: userInfo1.nickName,
              token: resData.token,
            };
            wx.setStorageSync("UserInfo", userInfo);
            store.commit("setToken", userInfo.token);
            store.commit("setUser", userInfo);

            //跳回前一个页面
            wx.navigateBack({
              delta: 1,
            });
          });
        },
        fail: (res) => {
          console.log("error", res);
        },
      });
    },
  },
};
</script>


<style>
.login {
  margin: 5px;
  text-align: center;
}
.login-account {
  padding-top: 15px;
}
</style>
